<template>
    <div class="source-container">
        <div class="page-header">
            <h1 class="page-title">溯源信息管理</h1>
            <p class="page-desc">管理产品溯源数据，支持新增、修改、删除和导出溯源码</p>
        </div>

        <el-card class="main-card" shadow="hover">
            <div class="button-group">
                <el-button type="primary" @click="opens(null)" class="operation-btn">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    <span>新增</span>
                </el-button>
                <el-button type="danger" @click="AllDelete" class="operation-btn"
                    :disabled="multipleSelection.length === 0">
                    <el-icon>
                        <Delete />
                    </el-icon>
                    <span>批量删除</span>
                </el-button>
                <div class="selection-info" v-if="multipleSelection.length > 0">
                    已选择 {{ multipleSelection.length }} 项
                </div>
            </div>

            <el-table ref="multipleTableRef" row-key="sourceId" @selection-change="handleSelectionChange"
                :data="tableData" style="width: 100%;" stripe highlight-current-row
                :header-cell-style="{ backgroundColor: '#f5f7fa', fontWeight: 'bold' }"
                :empty-text="loading ? '加载中...' : '暂无数据'">
                <el-table-column type="selection" width="55" />
                <el-table-column fixed type="index" label="序号" width="70" align="center" />
                <el-table-column prop="shopName" label="商品名称" width="120" align="center" />
                <el-table-column prop="shopBatch" label="生产批次" width="120" align="center" />
                <el-table-column prop="shopBestDate" label="保质期" width="80" align="center" />
                <el-table-column prop="shoppermit" label="生产许可证号" width="130" align="center" />
                <el-table-column prop="shopFirm" label="生产企业" width="200" align="center" />
                <el-table-column prop="shopPletene" label="信息完善度" width="100" align="center" />
                <el-table-column fixed="right" label="操作" min-width="220" align="center">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="Detail(scope.row.sourceId)" class="table-btn">
                            <el-icon>
                                <InfoFilled />
                            </el-icon>
                            详情
                        </el-button>
                        <el-button size="small" @click="opens(scope.row)" class="table-btn">
                            <el-icon>
                                <Edit />
                            </el-icon>
                            修改
                        </el-button>
                        <el-button type="success" size="small" @click="handleClick" class="table-btn">
                            <el-icon>
                                <Download />
                            </el-icon>
                            导出溯源码
                        </el-button>
                        <el-button type="danger" size="small" @click="DelSourse(scope.row.sourceId)" class="table-btn">
                            <el-icon>
                                <Delete />
                            </el-icon>
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 加载状态 -->
            <div v-if="loading" class="loading-container">
                <el-skeleton :rows="5" animated />
            </div>
        </el-card>

        <el-card class="pagination-card" shadow="hover" style="margin-top: 20px;">
            <el-pagination v-model:current-page="pages.pageindex" v-model:page-size="pages.pagesize"
                :page-sizes="[10, 20, 50, 100]" :background="true" layout="total, sizes, prev, pager, next, jumper"
                :total="pages.listCount" />
        </el-card>
        <el-dialog v-model="dialopen.Isopens" :title="dialopen.Istitle" width="600px" :before-close="handleClose"
            :close-on-click-modal="false" :close-on-press-escape="false">
            <el-form :model="form" label-width="120">
                <el-form-item label="商品名称" prop="shopId" required>
                    <el-select v-model="form.shopId" placeholder="请选择商品名称" clearable>
                        <el-option v-for="item in tableshop" :key="item.shopId" :label="item.shopName"
                            :value="item.shopId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="生产批次">
                    <el-input v-model="form.shopBatch" disabled prefix-icon="el-icon-date" />
                    <div class="form-tip">自动生成，格式：YYYYMMDD</div>
                </el-form-item>
                <el-form-item label="保质期(天)" prop="shopBestDate" required>
                    <el-input v-model="form.shopBestDate" type="number" placeholder="请输入保质期天数" min="1"
                        prefix-icon="el-icon-time" />
                </el-form-item>
                <el-form-item label="生产许可证号">
                    <el-input v-model="form.shoppermit" disabled prefix-icon="el-icon-document" />
                    <div class="form-tip">自动生成</div>
                </el-form-item>
                <el-form-item label="生产企业" prop="shopFirm" required>
                    <el-input v-model="form.shopFirm" placeholder="请输入生产企业名称" prefix-icon="el-icon-office-building" />
                </el-form-item>
                <el-form-item label="封面图" prop="shopImg">
                    <div class="upload-container">
                        <el-upload class="avatar-uploader" action="http://localhost:5002/api/Imgs/Imgs"
                            :show-file-list="false" :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload" :limit="1" drag>
                            <el-icon class="el-icon--upload">
                                <UploadFilled />
                            </el-icon>
                            <div class="el-upload__text">拖拽文件到此处或 <em>点击上传</em></div>
                            <template #tip>
                                <div class="el-upload__tip">
                                    只能上传 JPEG 格式图片，且不超过 2MB
                                </div>
                            </template>
                            <img v-if="form.shopImg" :src="form.shopImg" class="avatar" />
                        </el-upload>
                    </div>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialopen.Isopens = false">取消</el-button>
                    <el-button type="primary" @click="butopen" :loading="submitting">
                        {{ dialopen.buttons }}
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import httpaxios from '@/Httpaxios/Httpaxios'
import { onMounted, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import moment from 'moment'
import type { TableInstance } from 'element-plus'
import {
    Delete,
    Edit,
    Download,
    InfoFilled,
    UploadFilled
} from '@element-plus/icons-vue'
// 页面状态
const loading = ref(false)
const submitting = ref(false)

onMounted(() => {
    ShowSourse()
    GetShop()
})
const Detail = (id: any) => {
    router.push({
        path: '/Detail',
        query: {
            id: id
        }
    })
}
const dialopen = reactive({
    Isopens: false,
    Istitle: '',
    buttons: '',
    asd: true
})
const form = reactive({
    "sourceId": 0,
    "shopId": null,
    "shopBatch": moment().format("YYYYMMDD"),
    "shopBestDate": "",
    "shoppermit": "SC" + Math.random().toString().substring(2, 12),
    "shopFirm": "",
    "shopPletene": "80",
    "shopImg": "",
})
// 打开弹出框
const opens = (row: any) => {
    dialopen.Isopens = true
    if (row == null) {
        dialopen.Istitle = '新增溯源'
        dialopen.buttons = '新增'
        dialopen.asd = true
        form.shopId = null
        form.shopBatch = moment().format("YYYYMMDD")
        form.shopBestDate = ""
        form.shoppermit = "SC" + Math.random().toString().substring(2, 12)
        form.shopFirm = ""
        form.shopImg = ""
    }
    else {
        dialopen.Istitle = '修改溯源'
        dialopen.buttons = '修改'
        dialopen.asd = false
        form.sourceId = row.sourceId
        form.shopId = row.shopId
        form.shopBatch = row.shopBatch
        form.shopBestDate = row.shopBestDate
        form.shoppermit = row.shoppermit
        form.shopFirm = row.shopFirm
        form.shopImg = row.shopImg
    }
}
const butopen = () => {
    // 简单的表单验证
    if (!form.shopId) {
        ElMessage.warning('请选择商品名称')
        return
    }
    if (!form.shopBestDate || parseInt(form.shopBestDate) <= 0) {
        ElMessage.warning('请输入有效的保质期天数')
        return
    }
    if (!form.shopFirm) {
        ElMessage.warning('请输入生产企业名称')
        return
    }

    submitting.value = true

    if (dialopen.asd) {
        //新增
        httpaxios({
            url: 'http://localhost:5002/api/Source/AddSource',
            method: 'post',
            data: form
        })
            .then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.message)
                    dialopen.Isopens = false
                    ShowSourse()
                }
                else {
                    ElMessage.error(res.data.message)
                }
            })
            .catch(err => {
                console.error('新增溯源失败:', err)
                ElMessage.error('操作失败，请稍后重试')
            })
            .finally(() => {
                submitting.value = false
            })
    }
    else {
        //修改
        httpaxios({
            url: 'http://localhost:5002/api/Source/UpdateSource',
            method: 'post',
            data: form
        })
            .then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.message)
                    dialopen.Isopens = false
                    ShowSourse()
                }
                else {
                    ElMessage.error(res.data.message)
                }
            })
            .catch(err => {
                console.error('修改溯源失败:', err)
                ElMessage.error('操作失败，请稍后重试')
            })
            .finally(() => {
                submitting.value = false
            })
    }
}
const DelSourse = (id: any) => {
    ElMessageBox.confirm(
        '确认删除吗?',
        'Warning',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            httpaxios({
                url: 'http://localhost:5002/api/Source/DelSource',
                method: 'delete',
                params: {
                    id: id
                }
            })
                .then(res => {
                    if (res.data.code == 200) {
                        ElMessage.success(res.data.message)
                        ShowSourse()
                    }
                    else {
                        ElMessage.error(res.data.message)
                    }
                })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}
const handleClick = () => {
    ElNotification({
        title: '提示',
        message: '导出溯源码功能即将上线',
        type: 'info',
        duration: 3000
    })
}

const tableData = ref([])
const pages = reactive({
    pageindex: 1,
    pagesize: 15,
    listCount: 0,
})
watch((pages), () => {
    ShowSourse()
})
const ShowSourse = () => {
    loading.value = true
    httpaxios({
        url: 'http://localhost:5002/api/Source/ShowSource',
        method: 'get',
        params: {
            pageindex: pages.pageindex,
            pagesize: pages.pagesize
        }
    })
        .then(res => {
            tableData.value = res.data.data.data
            pages.listCount = res.data.data.listCount
        })
        .catch(err => {
            console.error('获取溯源数据失败:', err)
            ElMessage.error('获取数据失败，请稍后重试')
        })
        .finally(() => {
            loading.value = false
        })
}
const tableshop: any = ref([])
const GetShop = () => {
    httpaxios({
        url: 'http://localhost:5002/api/Source/GetShop',
        method: 'get',
    })
        .then(res => {
            tableshop.value = res.data.data
        })
        .catch(err => {
            console.error('获取商品数据失败:', err)
            ElMessage.error('获取商品数据失败')
        })
}
// 对话框关闭处理
const handleClose = () => {
    if (submitting.value) {
        ElMessage.warning('正在处理中，请稍候')
        return false
    }
    return true
}

// --------------------------------------------------上传图片---------------------------------------------
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import router from '@/router'
const imageUrl = ref('')
const handleAvatarSuccess = (img: any) => {
    form.shopImg = img
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('格式只能是jpeg!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不能超过2MB!')
        return false
    }
    return true
}
// -----------------------------------------------批量删除-----------------------------------------------
const multipleTableRef = ref<TableInstance>()
const multipleSelection = ref<any>([])
const handleSelectionChange = (val: any[]) => {
    multipleSelection.value = val
}
const AllDelete = () => {
    if (multipleSelection.value.length == 0) {
        ElMessage.error("最少选择一项")
        return
    }
    ElMessageBox.confirm(
        '确认删除吗?',
        'Warning',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            httpaxios({
                url: 'http://localhost:5002/api/Source/DelAll',
                method: 'delete',
                params: {
                    ids: multipleSelection.value.map((i: any) => i.sourceId).toString()
                }
            })
                .then(res => {
                    if (res.data.code == 200) {
                        ElMessage.success(res.data.message)
                        ShowSourse()
                    }
                    else {
                        ElMessage.error(res.data.message)
                    }
                })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}
</script>
<style scoped>
/* 主容器样式 */
.source-container {
    max-width: 1400px;
    margin: 0 auto;
    padding: 20px;
}

/* 页面头部 */
.page-header {
    margin-bottom: 30px;
}

.page-title {
    font-size: 28px;
    font-weight: 600;
    color: var(--el-text-color-primary);
    margin-bottom: 8px;
}

.page-desc {
    font-size: 14px;
    color: var(--el-text-color-secondary);
}

/* 卡片样式 */
.main-card,
.pagination-card {
    border-radius: 12px;
    transition: all 0.3s ease;
    overflow: hidden;
}

.main-card:hover,
.pagination-card:hover {
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

/* 按钮组 */
.button-group {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    gap: 10px;
    flex-wrap: wrap;
}

.operation-btn {
    display: flex;
    align-items: center;
    gap: 5px;
    padding: 8px 16px;
    border-radius: 6px;
    transition: all 0.3s ease;
}

.operation-btn:hover {
    transform: translateY(-1px);
}

.selection-info {
    margin-left: auto;
    color: var(--el-text-color-secondary);
    font-size: 14px;
    padding: 8px 16px;
    background-color: var(--el-bg-color-secondary);
    border-radius: 6px;
}

/* 表格按钮 */
.table-btn {
    margin-right: 8px;
    padding: 4px 12px;
}

.table-btn .el-icon {
    margin-right: 4px;
    font-size: 14px;
}

/* 加载状态 */
.loading-container {
    padding: 20px 0;
}

/* 表单样式 */
.el-form-item {
    margin-bottom: 24px;
}

.el-form-item__label {
    font-weight: 500;
}

.form-tip {
    font-size: 12px;
    color: var(--el-text-color-placeholder);
    margin-top: 4px;
}

/* 上传区域 */
.upload-container {
    margin-top: 5px;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
    border-radius: 8px;
    object-fit: cover;
}

/* 对话框样式 */
.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .source-container {
        padding: 10px;
    }

    .page-title {
        font-size: 24px;
    }

    .button-group {
        flex-direction: column;
        align-items: stretch;
    }

    .selection-info {
        margin-left: 0;
        text-align: center;
    }

    .el-table {
        font-size: 12px;
    }

    .el-table-column--fixed-right {
        min-width: 180px !important;
    }

    .table-btn {
        margin-right: 4px;
        margin-bottom: 4px;
        font-size: 12px;
        padding: 2px 8px;
    }

    .table-btn .el-icon {
        font-size: 12px;
        margin-right: 2px;
    }
}

@media (max-width: 480px) {
    .page-title {
        font-size: 20px;
    }

    .el-dialog {
        width: 90% !important;
    }

    .avatar-uploader .avatar {
        width: 120px;
        height: 120px;
    }
}
</style>